App.controller('searchBusResourceController', ['$rootScope', '$scope', '$state', 'Page', function ($rootScope, $scope, $state, Page) {

    Page.ajaxPostQuiet('media/bus/companys.do', null, function (resp) {
        $scope.companys = resp.data;
    });

    Page.ajaxGetQuiet('media/bus/mediatypes.do', null, function (resp) {
        $scope.mediaTypes = resp.data;
    });

    Page.ajaxPostQuiet('busType/query.do', null, function (resp) {
        $scope.busTypes = resp.data;
    });

    Page.ajaxPostQuiet('customer/queryCustomer.do', null, function (resp) {
        $scope.customerList = resp.data;
    });

    $scope.reset = function() {
        $scope.mediaResourceGrid.reset();
    };

    $scope.mediaResourceGrid = {
        mediaType:'',
        modelType : '',
        options : {
            bAutoWidth:false
        },
        column_defs: [

        ],
        initDynamicTable : function(mediaId,modelType){
            this.mediaType = mediaId;
            this.modelType = modelType;
            var busThRows = [];
            busThRows[0] = {style: "width: '20px'",col: '_index',name: ''};
            busThRows[1] = {style: "width: '70px'",col: 'plateNo',name: '车牌号'};
            busThRows[2] = {style: "width: '70px'",col: 'vehicleNo',name: '自编号'};
            busThRows[3] = {style: "width: '70px'",col: 'vehicleNoAbbr',name: '小自编号'};
            busThRows[4] = {style: "width: '70px'",col: 'lineNo',name: '线路'};
            busThRows[5] = {style: "width: '70px'",col: 'companyName',name: '营运公司'};
            busThRows[6] = {style: "width: '70px'",col: 'onlineDate',name: '上线年限'};
            busThRows[7] = {style: "width: '70px'",col: 'busType',name: '车型'};
            busThRows[8] = {style: "width: '70px'",col: 'busFloor',name: '双巴'};
            busThRows[9] = {style: "width: '70px'",col: 'airConditioned',name: '空调'};
            busThRows[10] = {style: "width: '70px'",col: 'busEnergy',name: '能源'};
            busThRows[11] = {style: "width: '70px'",col: 'businessType',name: '营运方式'};

            busThRows[12] = {style: "width: '70px'",col: 'resourceCode',name: '资源编号'};
            busThRows[13] = {style: "width: '70px'",col: 'customerName',name: '经营单位'};
            busThRows[14] = {style: "width: '70px'",col: 'billNo',name: '合同号'};
            if(this.modelType == "1" || this.modelType == undefined) {
                busThRows[15] = {style: "width: '70px'",col: 'content',name: '广告内容'};
            }

            $(busThRows).each(function(index, thead) {
                if(thead.col == 'plateNo'){
                    $scope.mediaResourceGrid.column_defs.push({
                        target : index,
                        template: function(row){
                            if(row.busStatus == "0") { //车辆已失效
                                return '<a href="javascript:void(0)" ed-click="viewBusMediaInfo">'+row.plateNo+'</a>'
                                    + '<a href="javascript:void(0);" ed-click="viewBusPosition" title="定位" class="icon-pointer" style="padding-left: 10px;font-size:13px;"></a>'
                                    + '<span style="font-size:13px;padding-left: 3px;color: red">失效</span>';
                            } else {
                                return '<a href="javascript:void(0)" ed-click="viewBusMediaInfo">'+row.plateNo+'</a>'
                                    + '<a href="javascript:void(0);" ed-click="viewBusPosition" title="定位" class="icon-pointer" style="padding-left: 10px;font-size:13px;"></a>';
                            }

                        }
                    });
                }
                if(thead.col == 'resourceCode'){
                    $scope.mediaResourceGrid.column_defs.push({
                        target : index,
                        template: function(row){
                            if(row.status == "0") {//媒体失效
                                return  '<a href="javascript:void(0)" ed-click="viewResource">' + row.resourceCode + '</a>'
                                    + '<span style="padding-left: 3px;font-size: 13px;color:red">失效</span>';
                            } else {
                                return  '<a href="javascript:void(0)" ed-click="viewResource">' + row.resourceCode + '</a>';
                            }

                        }
                    });
                }
                if(thead.col == 'proxyDate'){
                    $scope.mediaResourceGrid.column_defs.push({
                        target : index,
                        template: function(row){
                            if(row.startDate != '' && row.endDate != ''){
                                return  row.startDate + '至' + row.endDate;
                            }
                            return '';
                        }
                    });
                }
                if(thead.col == 'busType'){
                    $scope.mediaResourceGrid.column_defs.push({
                        target : index,
                        template: function(row){
                            var busType = row.busType;
                            var typeImg = "";
                            $($scope.busTypes).each(function(index, type) {
                                if(type.typeCode == row.busType){
                                    busType = type.typeName;
                                    typeImg = type.descImg;
                                    return;
                                }
                            });
                            if(typeImg == "") {
                                return '<span>'+ busType +'</span>';
                            } else {
                                return '<a class="mix-preview"  href="'+($scope.nginxPath + typeImg)+'" data-rel="fancybox-button">'+ busType +'</a>';
                            }

                        }
                    });
                }
                if(thead.col == 'customerName'){
                    $scope.mediaResourceGrid.column_defs.push({
                        target : index,
                        template: function(row){
                            var customerName = '';
                            $($scope.customerList).each(function(index, item) {
                                if(item.customerId == row.customerId){
                                    customerName = item.customerName;
                                    return;
                                }
                            });
                            return customerName;
                        }
                    });
                }
                if(thead.col == 'publishDate'){
                    $scope.mediaResourceGrid.column_defs.push({
                        target : index,
                        template: function(row){
                            if(row.publishTime != '' && row.publishOffTime!=''){
                            	return row.publishTime + '至' + row.publishOffTime;
                            }else{
                            	return '';
                            }
                            
                        }
                    });
                }
            });

            $scope.mediaResourceGrid.setDynamicTable(busThRows,{mediaType:$scope.mediaResourceGrid.mediaType, modelType : $scope.mediaResourceGrid.modelType});
        },
        viewBusMediaInfo : function(row){
            $scope.busMediaInfoModal.setBusId(row.busId).show();
        },
        viewBusPosition : function(row){
            $scope.busLineModal.init(row).show();
        },viewResource : function(row){
            $scope.resourceInfoModal.open(row.resourceId);
        }
    };

    $scope.$watch('mediaTypes', function (newValue, oldValue, $scope) {
        if(newValue){
            $scope.mediaResourceGrid.initDynamicTable($scope.mediaTypes[0].mediaId,$scope.mediaTypes[0].modelType);
        }
    });

    $scope.resourceInfoModal = {
        open : function(resourceId){
            this.show();
            $scope.resourceAdsGrid.query({resourceId:resourceId});
            $scope.resourceRightsGrid.query({resourceId:resourceId});
            Page.ajaxGetQuiet("media/resource/dynamicResourceDetailsHead.do",
                {mediaType : $scope.mediaResourceGrid.mediaType,resourceId : resourceId},function(resp){
                    $scope.resourceItemHead = angular.extend([],resp.data.headDatas);
                    $scope.resourceItemData = angular.extend({},resp.data.detailDatas[0]);
                });
        }
    };

    $scope.resourceAdsGrid = {
        options : {
            lazy : true
        }
    };

    $scope.resourceRightsGrid = {
        options : {
            lazy : true
        }
    };

    $scope.mediaResourceDetailGrid = {

    }

    $scope.busMediaInfoModal = {
        setBusId : function(busId){
            this.busId = busId;
            return this;
        },
        onShow : function(){
            Page.ajaxGetQuiet('media/bus/' + this.busId + '/info.do', null, function (resp) {
                $scope.mediaBus = resp.data;
                $($scope.busTypes).each(function(index, type) {
                    if(type.typeId == $scope.mediaBus.busType){
                        $scope.mediaBus.busTypeName = type.typeName;
                    }
                });
                $scope.mediaBus.busImgs = [];
		       	if($scope.mediaBus.busImg && $scope.mediaBus.busImg != ''){
		       		var imgs = $scope.mediaBus.busImg.split('|');
		       		$(imgs).each(function(index, img) {
		       			$scope.mediaBus.busImgs.push({
		       				path: img
		       			});
		       		});
		       	}
                
            });

        }
    };

    $scope.busLineModal = {
		init : function(bus){
			this.bus = bus;
			return this;
		},
		onShow : function(){
			this.setTitle("车辆定位【" + this.bus.vehicleNo + "】");
			var self = this;
	       	//高德
	       	var mapDiv = "busLineModalMapDiv";
			var width = $('#' + mapDiv).width();
			var height = $('#' + mapDiv).height();
			this.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:13,center: [114.296308, 30.595444]});
			
			Page.notice("正在定位...");
			Page.ajaxPostQuiet('media/bus/gps.do', {vehicleNo : this.bus.vehicleNo}, function (resp) {
				if(resp.data && resp.data.gpsdatatime){
					
					var po = AppUtil.GPS.gcj_encrypt(resp.data.latitude*1, resp.data.longitude*1);
					var infoWindow = new AMap.InfoWindow({
						content:self.bus.vehicleNo + '【运行线路：' + resp.data.lineName + '】【最后定位时间：' + resp.data.gpsdatatime +'】【方向角：' + resp.data.direction + '】'
					});
					var busMarker = new AMap.Marker({
						position: [po.lon, po.lat],
						icon: "./assets/admin/img/map_bus_orange.png",
						map:self.map
					}).on('click',function(e){
							infoWindow.open(self.map, e.target.getPosition());
					});
					infoWindow.open(self.map, busMarker.getPosition());
				}
		    });
			
			if(this.bus.lineNo){
				AMap.service(["AMap.LineSearch"], function() {
				    var linesearch = new AMap.LineSearch({
				    	city:'027',
				    	extensions:'all'
				    });
				    linesearch.search(self.bus.lineNo, function(status, result) {
			            if (status === 'complete' && result.info === 'OK' && result.lineInfo.length > 0) {
			              	var busArr = result.lineInfo[0].path;
	                		var stops = result.lineInfo[0].via_stops;
	                		var startPot = stops[0].location;
	                		var endPot = stops[stops.length - 1].location;
	                		
	                		new AMap.Marker({
					            map: self.map,
					            position: [startPot.lng, startPot.lat], //基点位置
					            icon: "http://webapi.amap.com/theme/v1.3/markers/n/start.png",
					            zIndex: 10
					        });
					        new AMap.Marker({
					            map: self.map,
					            position: [endPot.lng, endPot.lat], //基点位置
					            icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
					            zIndex: 10
					        });
					        //绘制乘车的路线
					        busPolyline = new AMap.Polyline({
					            map: self.map,
					            path: busArr,
					            strokeColor: "#09f",//线颜色
					            strokeOpacity: 0.8,//线透明度
					            strokeWeight: 5//线宽
					        });
			            }
			    	});
				});
			}
			
			setTimeout(function() {
				self.map.setFitView();
			},300);
			
   		}
	};


}]);